<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button
            type="primary" size="small"
            @click="onAdd('1','0')"
          >
            添加权限
          </el-button>
        </div>
        <el-table
          border
          :data="list"
          row-key="id"
        >
          <el-table-column
            label="名称"
            prop="name"
          />
          <el-table-column
            label="标识"
            prop="code"
          />
          <el-table-column
            label="描述"
            prop="description"
          />
          <el-table-column label="操作">
            <template #default="{row}">
              <el-button
                v-if="row.type===1"
                type="primary"
                @click="onAdd('2',row.id)"
              >
                添加
              </el-button>
              <el-button type="info" @click="onEdit(row)">编辑</el-button>
              <el-button type="danger" @click="onDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <el-dialog
        v-model="showDialog"
        title="弹层标题"
        @close="resetForm(ruleFormRef)"
      >
        <!-- 表单内容 -->
        <el-form
          ref="ruleFormRef"
          label-width="100px"
          :model="formData" 
          :rules="rules"
        >
          <el-form-item label="权限名称" prop="name">
            <el-input v-model="formData.name" />
          </el-form-item>
          <el-form-item label="权限标识" prop="code">
            <el-input v-model="formData.code" />
          </el-form-item>
          <el-form-item label="权限描述" prop="description">
            <el-input v-model="formData.description" />
          </el-form-item>
          <el-form-item label="权限启用">
            <el-switch
              v-model="formData.enVisible"
              active-text="启用"
              active-value="1"
              inactive-text="不启用"
              inactive-value="0"
            />
          </el-form-item>
        </el-form>

        <template #footer>
          <div style="text-align: right;">
            <el-button @click="resetForm(ruleFormRef)">取消</el-button>
            <el-button type="primary" @click="onSubmit(ruleFormRef)">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getPermissionList ,addPermission,updatePermission ,delPermission } from '@/api/permissions'
import { transTreeData } from '@/utils/transTreeData'
import {  FormInstance, FormRules ,FormValidateCallback } from 'element-plus'
//初始化
const list =ref<Array<TreeObj>>()
const originList=ref<FormPermission[]>()
const loadPermissionList =async() => {
  try {
    const res = await getPermissionList()
    console.log('getPermissionList',res)
    originList.value=res.data
    list.value=transTreeData(res.data)
  } catch (error) {
    console.log(error)
  }
}
loadPermissionList()
//控制弹层
const showDialog=ref(false)
//表单验证
//绑定from组件实例
const ruleFormRef = ref<FormInstance>()
//表单验证数据
let formData = reactive<Partial<FormPermission>>({
  name: '', // 名称
  code: '', // 权限标识
  description: '', // 描述
  enVisible: '0', // 开启
  pid: '', // 添加到哪个节点下
  type: '', // 类型
})
//自定义验证函数
const checkName=(rule: any, value: string, callback:any) => {
  let exsitName : string[]=[]
  if(originList.value) exsitName=originList.value.filter((item) => item.pid===formData.pid!).map(item=>item.name)
  if(isEdit.value) {
    exsitName=originList.value!.filter((item) => item.pid===formData.pid!&&item.id!==formData.id)
    .map((item) => item.name)
  }
  console.log('exsitName',exsitName)
  exsitName.includes(value) ? callback(new Error(`${ value }重复,请重新输入`)) : callback()
}
const checkCode=(rule: any, value: string, callback: any) => {
  let exsitCode : string[]=[]
  if(originList.value) exsitCode=originList.value.map((item) => item.code)
  if(isEdit.value) {
    exsitCode=originList.value!.filter((item) => item.id!==formData.id).map((item) => item.code)
  }
  exsitCode.includes(value) ? callback(new Error(`${ value }重复,请重新输入`)) : callback()
  console.log('exsitCode',exsitCode)
}
//表单验证规则
const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入权限名', trigger: 'blur' },
    { validator:checkName, trigger: 'blur' },
  ],
  code: [
    { required: true, message: '请输入编码', trigger: 'blur' },
    { validator:checkCode, trigger: 'blur' },

  ],
  description:[
    { required: true, message: '请输入权限描述', trigger: 'blur' },
  ],
})
//重置表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  showDialog.value=false
  Object.keys(formData).forEach((item) => formData[item as keyof typeof formData]='')
}
//兜底验证
const onSubmit = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async(valid) => {
    if(!valid) return false
    isEdit.value ? loadUpdatePermission(): loadAddPermission()

  })
}
//增加
const onAdd=( type :string,id:string) => {
  formData.type=type
  formData.pid=id
  showDialog.value=true
  isEdit.value=false
}
const loadAddPermission =async() => {
  try {
    const res = await addPermission(formData)
    console.log('addPermission',res)
    showDialog.value=false
    loadPermissionList()
  } catch (error) {
    console.log(error)
  }
}
//修改
const isEdit=ref(false)
const onEdit=(data:Partial<FormPermission>) => {
  isEdit.value=true
  showDialog.value=true
  formData=Object.assign(formData,data)
}
const loadUpdatePermission =async() => {
  try {
    const res = await updatePermission(formData)
    console.log('updatePermission',res)
    showDialog.value=false
    loadPermissionList()
  } catch (error) {
    console.log(error)
  }
}
//删除
const onDel =async(id:string) => {
  try {
    ElMessageBox.confirm('你确定删除吗?')
    const res = await delPermission(id)
    console.log('onDel',res)
    showDialog.value=false
    loadPermissionList()
  } catch (error) {
    console.log(error)
  }
}

</script>